package com.atguigu.eduservice.Listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.handler.GuliException;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import sun.tools.javac.ErrorConsumer;

/**
 * @Author zhaolie
 * @Date 2020/12/7 10:55 上午
 * @Version 1.0
 * @Description Excel文件监听类
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    // 因为不能给Spring进行管理,需要自己管理(需要手动传入)
    private EduSubjectService subjectService;

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        // 读取Excel中的内容
        if (subjectData == null) {
            throw new GuliException(20001, "文件数据为空");
        }

        // 添加一级分类
        EduSubject existOneSubject = existOneSubject(subjectData.getOneSubjectName(), subjectService);
        if (existOneSubject == null) {
            EduSubject eduSubject = new EduSubject();
            eduSubject.setTitle(subjectData.getOneSubjectName()); // 一级分类名称
            eduSubject.setParentId("0");
            eduSubject.setSort(0);
            subjectService.save(eduSubject);
        }

        // 添加二级分类
        String pid = existOneSubject.getId();
        EduSubject existTwoSubject = existTwoSubject(subjectData.getTwoSubjectName(), pid, subjectService);
        if (existTwoSubject == null) {
            EduSubject eduSubject = new EduSubject();
            eduSubject.setTitle(subjectData.getTwoSubjectName());
            eduSubject.setParentId(pid);
            eduSubject.setSort(0);
            System.out.println("二级分类==> " + eduSubject);
            subjectService.save(eduSubject);
        }
    }

    // 判断一级分类不能重复添加
    private EduSubject existOneSubject(String name, EduSubjectService subjectService) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", 0);
        return subjectService.getOne(wrapper);
    }


    // 判断二级分类不能重复添加
    private EduSubject existTwoSubject(String name, String pid, EduSubjectService subjectService) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        return subjectService.getOne(wrapper);
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
